package org.szy.plugin.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.util.UpdateEntity;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.noear.solon.data.annotation.Tran;
import org.szy.core.common.exception.BaseException;
import org.szy.core.common.param.CommonMoveParam;
import org.szy.core.common.param.CommonStatusParam;
import org.szy.core.common.service.impl.BaseServiceImpl;
import org.szy.core.common.uilts.TreeBuildFactory;
import org.szy.plugin.sys.entity.SysOrg;
import org.szy.plugin.sys.mapper.SysOrgMapper;
import org.szy.plugin.sys.param.SysOrgQueryParam;
import org.szy.plugin.sys.pojo.SysOrgTree;
import org.szy.plugin.sys.service.SysOrgService;

import java.util.List;
import java.util.Objects;

import static org.szy.plugin.sys.entity.table.SysOrgTableDef.SYS_ORG;

/**
 * 系统组织Service接口实现类
 *
 * @author wangbuhao
 * @since 2023-06-18 17:12:42
 **/
@ProxyComponent
public class SysOrgServiceImpl extends BaseServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {

    @Inject
    private SysOrgMapper sysOrgMapper;

    @Override
    public QueryWrapper qwByQuery(SysOrgQueryParam param) {
        QueryWrapper qw = new QueryWrapper();
        if (StrUtil.isNotEmpty(param.getColumnField())) {
            qw.select(param.getColumnField().split(","));
        }
        if (StrUtil.isNotEmpty(param.getName())) qw.and(SYS_ORG.NAME.eq(param.getName()));
        if (StrUtil.isNotEmpty(param.getCode())) qw.and(SYS_ORG.CODE.eq(param.getCode()));
        if (param.getStatus() != null) qw.and(SYS_ORG.STATUS.eq(param.getStatus()));
        qw.orderBy(SYS_ORG.SORT.asc());
        return qw;
    }

    @Override
    public List<SysOrg> list(SysOrgQueryParam param) {
        QueryWrapper qw = qwByQuery(param);
        return list(qw);
    }

    @Override
    public boolean add(SysOrg entity) {
        boolean exists = exists(SYS_ORG.CODE.eq(entity.getCode()));
        if (exists) throw new BaseException("组织代码已存在");
        entity.setPids(createNewPids(entity.getPid()));
        if (entity.getSort() == null) {
            long count = count();
            entity.setSort(Convert.toInt(count, 0) + 1);
        }
        return save(entity);
    }

    @Override
    public boolean edit(SysOrg entity) {
        boolean exists = exists(SYS_ORG.CODE.eq(entity.getCode()).and(SYS_ORG.ID.ne(entity.getId())));
        if (exists) throw new BaseException("组织代码已存在");
        if (Objects.equals(entity.getId(), entity.getPid()))
            throw new BaseException("上级组织不能选择自己");
        entity.setPids(createNewPids(entity.getPid()));
        return updateById(entity);
    }

    @Tran
    @Override
    public boolean deleteById(Long id) {
        return remove(SYS_ORG.ID.eq(id).or(SYS_ORG.PIDS.like(id)));
    }

    @Override
    public List<SysOrgTree> buildTrees(List<SysOrg> list) {
        List<SysOrgTree> lists = BeanUtil.copyToList(list, SysOrgTree.class);
        List<SysOrgTree> trees = new TreeBuildFactory<SysOrgTree>().doTreeBuild(lists);
        return trees;
    }

    @Tran
    @Override
    public boolean modifyStatus(CommonStatusParam param) {
        SysOrg entity = new SysOrg();
        entity.setStatus(param.getStatus());
        QueryWrapper qw = new QueryWrapper();
        qw.and(SYS_ORG.ID.eq(param.getId()).or(SYS_ORG.PIDS.like(param.getId())));
        return sysOrgMapper.updateByQuery(entity, qw) > 0;
    }


    @Override
    public boolean move(CommonMoveParam param) {
        SysOrg entity = this.getById(param.getId(), "id,pid,sort");
        QueryWrapper qw = new QueryWrapper().limit(1);
        qw.select("id,pid,sort").and(SYS_ORG.PID.eq(entity.getPid()));
        List<SysOrg> list;
        switch (param.getType()) {
            // 上移
            case "1":
                qw.and(SYS_ORG.SORT.lt(entity.getSort())).orderBy(SYS_ORG.SORT.desc());
                list = list(qw);
                if (list.size() == 0) throw new BaseException("没有可交换的上级组织");
                break;
            // 下移
            case "2":
                qw.and(SYS_ORG.SORT.gt(entity.getSort())).orderBy(SYS_ORG.SORT.asc());
                list = list(qw);
                if (list.size() == 0) throw new BaseException("没有可交换的下级组织");
                break;
            default:
                return false;
        }
        SysOrg moveEntity = list.get(0);

//        modify(SysOrg.class, "sort", moveEntity.getSort(), "id", entity.getId());
        SysOrg moveE = UpdateEntity.of(SysOrg.class, entity.getId());
        moveE.setSort(moveEntity.getSort());
        sysOrgMapper.update(moveE);

//        modify(SysOrg.class, "sort", entity.getSort(), "id", moveEntity.getId());
        SysOrg moveE2 = UpdateEntity.of(SysOrg.class, moveEntity.getId());
        moveE2.setSort(entity.getSort());
        sysOrgMapper.update(moveE2);

        return true;
    }


    @Override
    public List<String> listIdByPid(String pid) {
        QueryWrapper qw = new QueryWrapper();
        qw.select("id").and(SYS_ORG.PIDS.like(pid));
        return listAs(qw, String.class);
    }
}
